package app

import (
	"os"
	"path/filepath"
	"strings"

	"gitee.com/youkelike/ziam/zutils/homedir"
	"gitee.com/youkelike/zlog"
	"github.com/spf13/cobra"
	"github.com/spf13/pflag"
	"github.com/spf13/viper"
)

const configFileName = "config"

var cfgFile string

func init() {
	pflag.StringVarP(&cfgFile, "config", "c", cfgFile, "Read configuration from specified FILE, support JSON, YAML formats.")
}

func AddConfigFlag(basename string, fs *pflag.FlagSet) {
	fs.AddFlag(pflag.Lookup(configFileName))

	// 在参数解析后、命令执行前，读取配置文件
	cobra.OnInitialize(func() {
		err := LoadConfig(cfgFile, basename)
		if err != nil {
			os.Exit(1)
		}
	})
}

const (
	// RecommendedHomeDir defines the default directory used to place all iam service configurations.
	RecommendedHomeDir = ".ziam"

	// RecommendedEnvPrefix defines the ENV prefix used by all iam service.
	RecommendedEnvPrefix = "ZIAM"
)

func LoadConfig(cfg string, defaultName string) (err error) {
	if cfg != "" {
		viper.SetConfigFile(cfg)
	} else {
		viper.AddConfigPath(".")
		viper.AddConfigPath(filepath.Join(homedir.HomeDir(), RecommendedHomeDir))
		viper.AddConfigPath("D:/goproject/ziam/config")
		// 配置文件名，不带扩展名
		viper.SetConfigName(defaultName)
	}

	// Use config file from the flag.
	viper.SetConfigType("yaml")              // set the type of the configuration to yaml.
	viper.AutomaticEnv()                     // read in environment variables that match.
	viper.SetEnvPrefix(RecommendedEnvPrefix) // set ENVIRONMENT variables prefix to IAM.
	viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))

	// If a config file is found, read it in.
	err = viper.ReadInConfig()
	if err != nil {
		zlog.Warnw("WARNING: viper failed to discover and load the configuration file: %s", err.Error())
	}
	return
}
